/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    struct ListNode *head;
    if(l1->val < l2->val) {
        head = l1;
        l1 = l1->next;
    } else {
        head = l2;
        l2 = l2->next;
    }
    struct ListNode *p = head;
    while(l1 && l2) {
        if(l1->val < l2->val) {
            p->next = l1;
            l1 = l1->next;
        } else {
            p->next = l2;
            l2 = l2->next;
        }
        p = p->next;
    }
    p->next = ((l1 == NULL) ? l2 : l1);
    return head;
}

struct ListNode *sortList(struct ListNode *head)
{
    if(!head || !head->next)
        return head;

    struct ListNode *fast = head, *slow = head;
    while(fast->next && fast->next->next) {
        fast = fast->next->next;
        slow = slow->next;
    }
    fast = slow;
    slow = slow->next;
    fast->next = NULL;

    struct ListNode *l1 = sortList(head);
    struct ListNode *l2 = sortList(slow);
    return mergeTwoLists(l1, l2);
}